<template>
  <div class="formula-convert-container">
    <el-card class="page-header">
      <div class="header-content">
        <div class="title-area">
          <h1 class="page-title">Excel公式转换器</h1>
          <el-button 
            type="primary" 
            link 
            @click="$router.push('/tools/formulaConvert/demo')"
            icon="Histogram"
          >
            查看转换演示
          </el-button>
        </div>
        <p class="page-description">
          将Excel格式的公式转换为系统内部格式，支持IF、IFS、FIND、LEFT、MID、RIGHT等函数<br/>
          <el-tag type="warning" size="small">2025-01-14更新</el-tag> 
          新格式：函数调用使用 <code>FunctionName{参数}</code> 格式，参数用逗号分隔
        </p>
      </div>
    </el-card>

    <div class="content-wrapper">
      <el-row :gutter="20">
        <!-- 左侧：转换区域 -->
        <el-col :span="16">
          <el-tabs v-model="activeTab">
            <!-- 单个转换 -->
            <el-tab-pane label="单个转换" name="single">
              <el-card class="convert-card">
                <template #header>
                  <div class="card-header">
                    <span>单个公式转换</span>
                    <el-button 
                      type="primary" 
                      @click="convertSingle"
                      :loading="singleLoading"
                      :disabled="!singleForm.excelFormula"
                    >
                      转换
                    </el-button>
                  </div>
                </template>

                <el-form :model="singleForm" label-width="120px">
                  <el-form-item label="Excel公式" required>
                    <el-input
                      v-model="singleForm.excelFormula"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入Excel公式，例如：=IF(A1>100,&quot;大&quot;,&quot;小&quot;)"
                      clearable
                    />
                    <div class="form-tip">
                      支持的函数：IF、IFS、FIND、LEFT、MID、RIGHT等
                    </div>
                  </el-form-item>

                  <el-form-item label="转换结果">
                    <el-input
                      v-model="singleResult.converted"
                      type="textarea"
                      :rows="3"
                      readonly
                      placeholder="转换后的系统格式公式将在这里显示"
                    />
                    <div v-if="singleResult.validation !== null" class="result-status">
                      <el-tag 
                        :type="singleResult.validation ? 'success' : 'warning'"
                        size="small"
                      >
                        {{ singleResult.validation ? '验证通过' : '需要检查' }}
                      </el-tag>
                    </div>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-tab-pane>

            <!-- 批量转换 -->
            <el-tab-pane label="批量转换" name="batch">
              <el-card class="convert-card">
                <template #header>
                  <div class="card-header">
                    <span>批量公式转换</span>
                    <div>
                      <el-button @click="addFormula" icon="Plus">添加公式</el-button>
                      <el-button 
                        type="primary" 
                        @click="convertBatch"
                        :loading="batchLoading"
                        :disabled="batchForms.length === 0"
                      >
                        批量转换
                      </el-button>
                    </div>
                  </div>
                </template>

                <div class="batch-forms">
                  <div 
                    v-for="(form, index) in batchForms" 
                    :key="index"
                    class="batch-form-item"
                  >
                    <div class="form-header">
                      <span class="form-index">公式 {{ index + 1 }}</span>
                      <el-button
                        type="danger"
                        link
                        @click="removeFormula(index)"
                        icon="Delete"
                      >
                        删除
                      </el-button>
                    </div>
                    <el-input
                      v-model="form.formula"
                      type="textarea"
                      :rows="2"
                      :placeholder="`请输入第${index + 1}个Excel公式`"
                      clearable
                    />
                  </div>

                  <el-empty 
                    v-if="batchForms.length === 0"
                    description="请添加需要转换的Excel公式"
                    :image-size="100"
                  />
                </div>

                <!-- 批量转换结果 -->
                <div v-if="batchResults.length > 0" class="batch-results">
                  <el-divider>转换结果</el-divider>
                  <div class="result-summary">
                    <el-tag type="info">总计: {{ batchSummary.total }}</el-tag>
                    <el-tag type="success">成功: {{ batchSummary.success }}</el-tag>
                    <el-tag type="danger">失败: {{ batchSummary.failed }}</el-tag>
                  </div>

                  <el-table :data="batchResults" stripe>
                    <el-table-column prop="index" label="序号" width="80" />
                    <el-table-column prop="original" label="原始公式" min-width="200" show-overflow-tooltip />
                    <el-table-column prop="converted" label="转换结果" min-width="200" show-overflow-tooltip />
                    <el-table-column prop="status" label="状态" width="100">
                      <template #default="{ row }">
                        <el-tag :type="row.status === '成功' ? 'success' : 'danger'" size="small">
                          {{ row.status }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column prop="validation" label="验证" width="100">
                      <template #default="{ row }">
                        <el-tag 
                          v-if="row.validation"
                          :type="row.validation === '通过' ? 'success' : 'warning'" 
                          size="small"
                        >
                          {{ row.validation }}
                        </el-tag>
                      </template>
                    </el-table-column>
                  </el-table>

                  <div class="result-actions">
                    <el-button @click="downloadReport" icon="Download">下载转换报告</el-button>
                    <el-button @click="copyAllResults" icon="CopyDocument">复制所有结果</el-button>
                  </div>
                </div>
              </el-card>
            </el-tab-pane>

            <!-- 电器公式转换 -->
            <el-tab-pane label="电器公式转换" name="electrical">
              <el-card class="convert-card">
                <template #header>
                  <div class="card-header">
                    <span>Excel公式转电器公式</span>
                    <el-button 
                      type="primary" 
                      @click="convertElectricalSingle"
                      :loading="electricalLoading"
                      :disabled="!electricalForm.excelFormula"
                    >
                      转换
                    </el-button>
                  </div>
                </template>

                <el-alert
                  title="电器公式转换说明"
                  type="info"
                  :closable="false"
                  show-icon
                >
                  此功能用于将标准Excel公式转换为电器公式格式，支持IF、IFS、AND、OR、LET等函数，使用大括号{}替代小括号()。
                </el-alert>

                <el-form :model="electricalForm" label-width="120px" style="margin-top: 20px;">
                  <el-form-item label="Excel公式" required>
                    <el-input
                      v-model="electricalForm.excelFormula"
                      type="textarea"
                      :rows="4"
                      placeholder="请输入Excel公式，例如：IF(AND(A1>0, B1<=10), LET(x, A1+B1, x*2), 0)"
                      clearable
                    />
                    <div class="form-tip">
                      支持的函数：IF、IFS、AND、OR、LET、LEFT、MID、RIGHT、FIND等
                    </div>
                  </el-form-item>

                  <el-form-item label="转换结果">
                    <el-input
                      v-model="electricalResult.converted"
                      type="textarea"
                      :rows="4"
                      readonly
                      placeholder="转换后的电器公式将在这里显示"
                    />
                    <div v-if="electricalResult.success !== null" class="result-status">
                      <el-tag 
                        :type="electricalResult.success ? 'success' : 'danger'"
                        size="small"
                      >
                        {{ electricalResult.success ? '转换成功' : '转换失败' }}
                      </el-tag>
                      <el-tag 
                        v-if="electricalResult.validation !== null"
                        :type="electricalResult.validation ? 'success' : 'warning'"
                        size="small"
                        style="margin-left: 10px;"
                      >
                        {{ electricalResult.validation ? '格式验证通过' : '格式需要检查' }}
                      </el-tag>
                    </div>
                  </el-form-item>
                </el-form>

                <!-- 批量转换 -->
                <el-divider>批量转换</el-divider>
                <div class="electrical-batch">
                  <div class="batch-header">
                    <span>批量Excel公式转电器公式：</span>
                    <div>
                      <el-button @click="addElectricalFormula" size="small" icon="Plus">添加公式</el-button>
                      <el-button 
                        @click="convertElectricalBatch" 
                        type="primary" 
                        size="small"
                        :loading="electricalBatchLoading"
                        :disabled="electricalBatchForms.length === 0"
                      >
                        批量转换
                      </el-button>
                    </div>
                  </div>
                  
                  <div class="batch-forms">
                    <div 
                      v-for="(form, index) in electricalBatchForms" 
                      :key="index"
                      class="batch-form-item"
                    >
                      <div class="form-header">
                        <span class="form-index">公式 {{ index + 1 }}</span>
                        <el-button
                          type="danger"
                          link
                          @click="removeElectricalFormula(index)"
                          icon="Delete"
                        >
                          删除
                        </el-button>
                      </div>
                      <el-input
                        v-model="form.formula"
                        type="textarea"
                        :rows="2"
                        :placeholder="`请输入第${index + 1}个Excel公式`"
                        clearable
                      />
                    </div>

                    <el-empty 
                      v-if="electricalBatchForms.length === 0"
                      description="请添加需要转换的Excel公式"
                      :image-size="100"
                    />
                  </div>

                  <!-- 批量转换结果 -->
                  <div v-if="electricalBatchResults.length > 0" class="batch-results">
                    <el-divider>转换结果</el-divider>
                    <div class="result-summary">
                      <el-tag type="info">总计: {{ electricalBatchSummary.total }}</el-tag>
                      <el-tag type="success">成功: {{ electricalBatchSummary.success }}</el-tag>
                      <el-tag type="danger">失败: {{ electricalBatchSummary.failed }}</el-tag>
                    </div>

                    <el-table :data="electricalBatchResults" stripe>
                      <el-table-column prop="index" label="序号" width="80" />
                      <el-table-column prop="original" label="原始公式" min-width="200" show-overflow-tooltip />
                      <el-table-column prop="converted" label="转换结果" min-width="200" show-overflow-tooltip />
                      <el-table-column prop="status" label="状态" width="100">
                        <template #default="{ row }">
                          <el-tag :type="row.status === '成功' ? 'success' : 'danger'" size="small">
                            {{ row.status }}
                          </el-tag>
                        </template>
                      </el-table-column>
                      <el-table-column prop="validation" label="验证" width="100">
                        <template #default="{ row }">
                          <el-tag 
                            v-if="row.validation"
                            :type="row.validation === '通过' ? 'success' : 'warning'" 
                            size="small"
                          >
                            {{ row.validation }}
                          </el-tag>
                        </template>
                      </el-table-column>
                    </el-table>

                    <div class="result-actions">
                      <el-button @click="downloadElectricalReport" icon="Download">下载转换报告</el-button>
                      <el-button @click="copyElectricalResults" icon="CopyDocument">复制所有结果</el-button>
                    </div>
                  </div>
                </div>

                <!-- 转换示例 -->
                <el-divider>转换示例</el-divider>
                <div class="electrical-examples">
                  <div class="example-item">
                    <h5>输入示例：</h5>
                    <pre class="example-code">IF(AND(A1>0, B1<=10), LET(x, A1+B1, x*2), 0)</pre>
                  </div>
                  <div class="example-item">
                    <h5>输出示例：</h5>
                    <pre class="example-code">IF{AND{A1>0, B1<=10}, LET{x, A1+B1, x*2}, 0}</pre>
                  </div>
                  <div class="example-item">
                    <h5>支持的函数：</h5>
                    <p class="function-support">IF、IFS、AND、OR、LET、LEFT、MID、RIGHT、FIND、UPPER、LOWER、TRIM</p>
                  </div>
                </div>
              </el-card>
            </el-tab-pane>

            <!-- 特殊业务规则转换 -->
            <el-tab-pane label="特殊业务规则" name="business">
              <el-card class="convert-card">
                <template #header>
                  <div class="card-header">
                    <span>特殊业务规则转换</span>
                    <el-button 
                      type="primary" 
                      @click="handleConvertBusinessRule"
                      :loading="businessLoading"
                      :disabled="!businessForm.formula"
                    >
                      转换
                    </el-button>
                  </div>
                </template>

                <el-alert
                  title="特殊业务规则转换说明"
                  type="info"
                  :closable="false"
                  show-icon
                >
                  此功能用于将标准Excel公式转换为带倍数扩展的业务规则格式，适用于需要将单个条件扩展为多个匹配值的场景。
                </el-alert>

                <el-form :model="businessForm" label-width="120px" style="margin-top: 20px;">
                  <el-form-item label="Excel公式" required>
                    <el-input
                      v-model="businessForm.formula"
                      type="textarea"
                      :rows="4"
                      placeholder="请输入特殊Excel公式，例如：@IFS(LEFT(D8,5)=&quot;60*80&quot;,&quot;19*35*1.2&quot;,OR(LEFT(D8,5)=&quot;63*90&quot;,LEFT(D8,5)=&quot;70*90&quot;),&quot;24*40*1.2&quot;)"
                      clearable
                    />
                    <div class="form-tip">
                      专门处理包含尺寸匹配和倍数扩展的IFS公式转换
                    </div>
                  </el-form-item>

                  <el-form-item label="变量名">
                    <el-input
                      v-model="businessForm.variableName"
                      placeholder="可选：指定变量名（如立柱片下@型号），为空时自动识别"
                      clearable
                    />
                  </el-form-item>

                  <el-form-item label="转换结果">
                    <el-input
                      v-model="businessResult.converted"
                      type="textarea"
                      :rows="4"
                      readonly
                      placeholder="转换后的业务规则格式将在这里显示"
                    />
                    <div v-if="businessResult.success !== null" class="result-status">
                      <el-tag 
                        :type="businessResult.success ? 'success' : 'danger'"
                        size="small"
                      >
                        {{ businessResult.success ? '转换成功' : '转换失败' }}
                      </el-tag>
                      <span v-if="businessResult.message" style="margin-left: 10px; color: #666;">
                        {{ businessResult.message }}
                      </span>
                    </div>
                  </el-form-item>
                </el-form>

                <!-- 倍数规则管理 -->
                <el-divider>倍数规则管理</el-divider>
                <div class="rules-management">
                  <div class="rules-header">
                    <span>当前倍数规则：</span>
                    <div>
                      <el-button @click="loadBusinessRules" size="small" icon="Refresh">刷新规则</el-button>
                      <el-button @click="showRulesDialog = true" size="small" icon="Setting">管理规则</el-button>
                    </div>
                  </div>
                  
                  <div class="rules-display" v-if="currentRules && Object.keys(currentRules).length > 0">
                    <el-table :data="rulesTableData" size="small" max-height="200">
                      <el-table-column prop="size" label="尺寸规格" width="100" />
                      <el-table-column prop="multipliers" label="倍数值" min-width="200" />
                    </el-table>
                  </div>
                  
                  <el-empty 
                    v-else
                    description="暂无倍数规则配置"
                    :image-size="60"
                  />
                </div>

                <!-- 示例说明 -->
                <el-divider>转换示例</el-divider>
                <div class="business-examples">
                  <div class="example-item">
                    <h5>输入示例：</h5>
                    <pre class="example-code">@IFS(LEFT(D8,5)="60*80","19*35*1.2",OR(LEFT(D8,5)="63*90",LEFT(D8,5)="70*90"),"24*40*1.2",OR(LEFT(D8,6)="65*100",LEFT(D8,6)="85*100"),"29*50*1.35")</pre>
                  </div>
                  <div class="example-item">
                    <h5>输出示例：</h5>
                    <pre class="example-code">{IFS:立柱片下@型号:60*80*1.8,60*80*1.2=19*35*1.2|63*90*2,70*90*1.8,70*90*2=24*40*1.2|65*100*1.8,65*100*2,85*100*2,85*100*2.5=29*50*1.35}</pre>
                  </div>
                </div>
              </el-card>
            </el-tab-pane>
          </el-tabs>
        </el-col>

        <!-- 右侧：配置区域 -->
        <el-col :span="8">
          <el-card class="config-card">
            <template #header>
              <div class="card-header">
                <span>单元格映射配置</span>
                <div>
                  <el-button @click="loadDefaultMapping" size="small">载入默认</el-button>
                  <el-button @click="addMapping" size="small" icon="Plus">添加</el-button>
                </div>
              </div>
            </template>

            <div class="mapping-list">
              <div 
                v-for="(mapping, index) in mappings" 
                :key="index"
                class="mapping-item"
              >
                <div class="mapping-inputs">
                  <el-input
                    v-model="mapping.cellRef"
                    placeholder="单元格(如A1)"
                    size="small"
                  />
                  <span class="mapping-arrow">→</span>
                  <el-input
                    v-model="mapping.variableName"
                    placeholder="变量名(如主框架@宽度)"
                    size="small"
                  />
                </div>
                <el-button
                  type="danger"
                  link
                  @click="removeMapping(index)"
                  icon="Delete"
                  size="small"
                />
              </div>

              <el-empty 
                v-if="mappings.length === 0"
                description="请添加单元格映射"
                :image-size="80"
              />
            </div>

            <el-divider>使用说明</el-divider>
            <div class="help-content">
              <h4>支持的函数转换：</h4>
              <ul class="function-list">
                <li><code>IF(条件,值1,值2)</code> → <code>{IF:条件,值1,值2}</code></li>
                <li><code>IFS(...)</code> → <code>{IFS:参考值:...}</code></li>
                <li><code>OR(条件1,条件2,...)</code> → <code>(条件1 OR 条件2 OR ...)</code> <span class="new-tag">新增</span></li>
                <li><code>LEFT(字符串,长度)</code> → <code>{LEFT:字符串:长度}</code></li>
                <li><code>MID(字符串,起始,长度)</code> → <code>{MID:字符串:起始:长度}</code></li>
                <li><code>RIGHT(字符串,长度)</code> → <code>{RIGHT:字符串:长度}</code></li>
                <li><code>FIND(查找,字符串)</code> → <code>{FIND:字符串:查找}</code></li>
              </ul>

              <h4>特殊前缀支持：</h4>
              <ul class="prefix-list">
                <li><code>@IFS(...)</code> 等价于 <code>=IFS(...)</code> <span class="new-tag">新增</span></li>
                <li><code>=IF(...)</code> 标准Excel公式格式</li>
              </ul>

              <h4>复杂公式示例：</h4>
              <div class="example-box">
                <p><strong>原始：</strong><br>
                <code class="example-code">@IFS(LEFT(D8,5)="60*80","19*35*1.2",OR(LEFT(D8,5)="63*90",LEFT(D8,5)="70*90"),"24*40*1.2")</code></p>
                <p><strong>转换：</strong><br>
                <code class="example-code">{IFS:立柱片下@规格:({LEFT:{立柱片下@规格}:5}="60*80")="19*35*1.2"|({LEFT:{立柱片下@规格}:5}="63*90" OR {LEFT:{立柱片下@规格}:5}="70*90")="24*40*1.2"}</code></p>
              </div>

              <h4>变量名格式：</h4>
              <p class="help-text">
                格式：<code>物料名@属性类型</code><br>
                示例：<code>主框架@宽度</code>、<code>立柱片下@规格</code>
              </p>

              <h4>⚠️ 注意事项：</h4>
              <ul class="warning-list">
                <li>复杂嵌套公式可能需要手动调整参考值</li>
                <li>确保单元格映射配置完整（特别是D8等特殊单元格）</li>
                <li>转换后请验证公式的逻辑正确性</li>
              </ul>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 倍数规则管理对话框 -->
    <el-dialog
      v-model="showRulesDialog"
      title="倍数规则管理"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="rules-dialog-content">
        <el-alert
          title="倍数规则说明"
          type="info"
          :closable="false"
          show-icon
        >
          用于定义不同尺寸规格对应的倍数值，在特殊业务规则转换时会自动应用这些倍数扩展单个条件。
        </el-alert>

        <div style="margin-top: 20px;">
          <h4>当前规则：</h4>
          <el-table :data="rulesTableData" size="small" max-height="300">
            <el-table-column prop="size" label="尺寸规格" width="150" />
            <el-table-column prop="multipliers" label="倍数值" />
            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <el-button
                  type="danger"
                  link
                  size="small"
                  @click="removeRule(row.size)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div style="margin-top: 20px;">
          <h4>添加新规则：</h4>
          <el-form :model="newRule" label-width="100px" size="small">
            <el-form-item label="尺寸规格：">
              <el-input
                v-model="newRule.size"
                placeholder="如：60*80"
                style="width: 150px;"
              />
            </el-form-item>
            <el-form-item label="倍数值：">
              <el-input
                v-model="newRule.multipliers"
                placeholder="如：1.8,1.2（用逗号分隔）"
                style="width: 200px;"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addNewRule" size="small">
                添加规则
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showRulesDialog = false">取消</el-button>
          <el-button type="primary" @click="saveRules">保存规则</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  convertSingleFormula, 
  convertBatchFormulas, 
  getDefaultMapping,
  convertBusinessRule,
  getBusinessRules,
  updateBusinessRules,
  convertSingleElectricalFormula,
  convertBatchElectricalFormulas,
  getElectricalFormulaExample,
  validateElectricalFormula
} from '@/api/formulaConvert'
import type { 
  CellMappingItem, 
  ConversionItem,
  BusinessRuleConvertRequest,
  BusinessRuleConvertResponse
} from '@/api/formulaConvert/type'

// 响应式数据
const activeTab = ref('single')
const singleLoading = ref(false)
const batchLoading = ref(false)

// 单个转换表单
const singleForm = reactive({
  excelFormula: ''
})

// 单个转换结果
const singleResult = reactive({
  converted: '',
  validation: null as boolean | null
})

// 批量转换表单
const batchForms = ref<{ formula: string }[]>([])

// 批量转换结果
const batchResults = ref<ConversionItem[]>([])
const batchReport = ref('')

// 单元格映射
const mappings = ref<CellMappingItem[]>([])

// 特殊业务规则转换
const businessLoading = ref(false)
const businessForm = reactive({
  formula: '',
  variableName: ''
})

const businessResult = reactive({
  success: null as boolean | null,
  converted: '',
  message: ''
})

// 电器公式转换相关数据
const electricalLoading = ref(false)
const electricalBatchLoading = ref(false)
const electricalForm = reactive({
  excelFormula: ''
})
const electricalResult = reactive({
  success: null as boolean | null,
  converted: '',
  validation: null as boolean | null
})
const electricalBatchForms = ref<{ formula: string }[]>([])
const electricalBatchResults = ref<any[]>([])
const electricalBatchReport = ref('')

// 倍数规则管理
const showRulesDialog = ref(false)
const currentRules = ref<Record<string, number[]>>({})
const newRule = reactive({
  size: '',
  multipliers: ''
})
const rulesTableData = computed(() => {
  return Object.entries(currentRules.value).map(([size, multipliers]) => ({
    size,
    multipliers: multipliers.join(', ')
  }))
})

// 计算属性
const mappingObject = computed(() => {
  const obj: Record<string, string> = {}
  mappings.value.forEach(mapping => {
    if (mapping.cellRef && mapping.variableName) {
      obj[mapping.cellRef] = mapping.variableName
    }
  })
  return obj
})

const batchSummary = computed(() => {
  const total = batchResults.value.length
  const success = batchResults.value.filter(item => item.status === '成功').length
  const failed = total - success
  return { total, success, failed }
})

const electricalBatchSummary = computed(() => {
  const total = electricalBatchResults.value.length
  const success = electricalBatchResults.value.filter(item => item.status === '成功').length
  const failed = total - success
  return { total, success, failed }
})

// 单个转换
const convertSingle = async () => {
  if (!singleForm.excelFormula) {
    ElMessage.warning('请输入Excel公式')
    return
  }

  singleLoading.value = true
  try {
    const response = await convertSingleFormula({
      excelFormula: singleForm.excelFormula,
      cellVariableMap: mappingObject.value
    })

    console.log(response.code)

    if (response.code === 200) {
      singleResult.converted = response.data.convertedFormula
      singleResult.validation = response.data.validation || true
      ElMessage.success(response.message || '转换成功')
    } else {
      ElMessage.error(response.error || response.message || '转换失败')
    }
  } catch (error) {
    console.error('转换失败:', error)
    ElMessage.error('转换失败，请检查网络连接')
  } finally {
    singleLoading.value = false
  }
}

// 添加公式
const addFormula = () => {
  batchForms.value.push({ formula: '' })
}

// 删除公式
const removeFormula = (index: number) => {
  batchForms.value.splice(index, 1)
}

// 批量转换
const convertBatch = async () => {
  const formulas = batchForms.value
    .map(form => form.formula)
    .filter(formula => formula.trim())

  if (formulas.length === 0) {
    ElMessage.warning('请至少输入一个Excel公式')
    return
  }

  batchLoading.value = true
  try {
    const response = await convertBatchFormulas({
      excelFormulas: formulas,
      cellVariableMap: mappingObject.value
    })

    if (response.success) {
      batchResults.value = response.conversions
      batchReport.value = response.report
      ElMessage.success(`批量转换完成，成功${batchSummary.value.success}个，失败${batchSummary.value.failed}个`)
    } else {
      ElMessage.error(response.error || '批量转换失败')
    }
  } catch (error) {
    console.error('批量转换失败:', error)
    ElMessage.error('批量转换失败，请检查网络连接')
  } finally {
    batchLoading.value = false
  }
}

// 添加映射
const addMapping = () => {
  mappings.value.push({
    cellRef: '',
    variableName: ''
  })
}

// 删除映射
const removeMapping = (index: number) => {
  mappings.value.splice(index, 1)
}

// 载入默认映射
const loadDefaultMapping = async () => {
  try {
    const response = await getDefaultMapping()
    if (response.success) {
      mappings.value = Object.entries(response.mapping).map(([cellRef, variableName]) => ({
        cellRef,
        variableName
      }))
      ElMessage.success('默认映射载入成功')
    }
  } catch (error) {
    console.error('载入默认映射失败:', error)
    ElMessage.error('载入默认映射失败')
  }
}

// 下载转换报告
const downloadReport = () => {
  if (!batchReport.value) {
    ElMessage.warning('没有可下载的报告')
    return
  }

  const blob = new Blob([batchReport.value], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `Excel公式转换报告_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.txt`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

// 复制所有结果
const copyAllResults = () => {
  const results = batchResults.value
    .filter(item => item.status === '成功')
    .map(item => item.converted)
    .join('\n')

  if (!results) {
    ElMessage.warning('没有可复制的成功结果')
    return
  }

  navigator.clipboard.writeText(results).then(() => {
    ElMessage.success('转换结果已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}

// 特殊业务规则转换
const handleConvertBusinessRule = async () => {
  if (!businessForm.formula) {
    ElMessage.warning('请输入Excel公式')
    return
  }

  businessLoading.value = true
  try {
    const response = await convertBusinessRule({
      formula: businessForm.formula,
      variableName: businessForm.variableName || undefined
    })

    if (response.code === 200) {
      businessResult.success = true
      businessResult.converted = response.data.convertedFormula
      businessResult.message = response.message || '转换成功'
      ElMessage.success(response.message || '特殊业务规则转换成功')
    } else {
      businessResult.success = false
      businessResult.converted = ''
      businessResult.message = response.error || response.message || '转换失败'
      ElMessage.error(response.error || response.message || '转换失败')
    }
  } catch (error) {
    console.error('特殊业务规则转换失败:', error)
    businessResult.success = false
    businessResult.converted = ''
    businessResult.message = '网络错误'
    ElMessage.error('转换失败，请检查网络连接')
  } finally {
    businessLoading.value = false
  }
}

// 加载倍数规则
const loadBusinessRules = async () => {
  try {
    const response = await getBusinessRules()
    if (response.code === 200) {
      currentRules.value = response.rules
      ElMessage.success('倍数规则加载成功')
    } else {
      ElMessage.error(response.message || '加载倍数规则失败')
    }
  } catch (error) {
    console.error('加载倍数规则失败:', error)
    ElMessage.error('加载倍数规则失败，请检查网络连接')
  }
}

// 删除规则
const removeRule = (size: string) => {
  delete currentRules.value[size]
  ElMessage.success('规则删除成功')
}

// 添加新规则
const addNewRule = () => {
  if (!newRule.size || !newRule.multipliers) {
    ElMessage.warning('请填写完整的规则信息')
    return
  }

  try {
    const multipliers = newRule.multipliers.split(',').map(m => parseFloat(m.trim()))
    if (multipliers.some(m => isNaN(m))) {
      ElMessage.error('倍数值格式错误，请使用数字并用逗号分隔')
      return
    }

    currentRules.value[newRule.size] = multipliers
    newRule.size = ''
    newRule.multipliers = ''
    ElMessage.success('规则添加成功')
  } catch (error) {
    ElMessage.error('倍数值格式错误')
  }
}

// 保存规则
const saveRules = async () => {
  try {
    await updateBusinessRules(currentRules.value)
    ElMessage.success('规则保存成功')
    showRulesDialog.value = false
  } catch (error) {
    console.error('保存规则失败:', error)
    ElMessage.error('保存规则失败，请检查网络连接')
  }
}

// 电器公式转换方法
const convertElectricalSingle = async () => {
  if (!electricalForm.excelFormula) {
    ElMessage.warning('请输入Excel公式')
    return
  }

  electricalLoading.value = true
  try {
    const response = await convertSingleElectricalFormula({
      excelFormula: electricalForm.excelFormula
    })

    if (response.code === 200) {
      electricalResult.success = true
      electricalResult.converted = response.data.convertedFormula
      electricalResult.validation = response.data.validation
      ElMessage.success('电器公式转换成功')
    } else {
      electricalResult.success = false
      electricalResult.converted = ''
      electricalResult.validation = null
      ElMessage.error(response.message || '转换失败')
    }
  } catch (error) {
    console.error('电器公式转换失败:', error)
    electricalResult.success = false
    electricalResult.converted = ''
    electricalResult.validation = null
    ElMessage.error('转换失败，请检查网络连接')
  } finally {
    electricalLoading.value = false
  }
}

const addElectricalFormula = () => {
  electricalBatchForms.value.push({ formula: '' })
}

const removeElectricalFormula = (index: number) => {
  electricalBatchForms.value.splice(index, 1)
}

const convertElectricalBatch = async () => {
  const formulas = electricalBatchForms.value
    .map(form => form.formula)
    .filter(formula => formula.trim())

  if (formulas.length === 0) {
    ElMessage.warning('请至少输入一个Excel公式')
    return
  }

  electricalBatchLoading.value = true
  try {
    const response = await convertBatchElectricalFormulas({
      excelFormulas: formulas
    })

    if (response.code === 200) {
      electricalBatchResults.value = response.data.results
      electricalBatchReport.value = response.data.report
      ElMessage.success(`批量转换完成，成功${response.data.successCount}个，失败${response.data.failedCount}个`)
    } else {
      ElMessage.error(response.message || '批量转换失败')
    }
  } catch (error) {
    console.error('批量电器公式转换失败:', error)
    ElMessage.error('批量转换失败，请检查网络连接')
  } finally {
    electricalBatchLoading.value = false
  }
}

const downloadElectricalReport = () => {
  if (!electricalBatchReport.value) {
    ElMessage.warning('没有可下载的报告')
    return
  }

  const blob = new Blob([electricalBatchReport.value], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `电器公式转换报告_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.txt`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

const copyElectricalResults = () => {
  const results = electricalBatchResults.value
    .filter(item => item.status === '成功')
    .map(item => item.converted)
    .join('\n')

  if (!results) {
    ElMessage.warning('没有可复制的成功结果')
    return
  }

  navigator.clipboard.writeText(results).then(() => {
    ElMessage.success('转换结果已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}

// 初始化
const init = () => {
  // 添加一些默认映射示例
  mappings.value = [
    { cellRef: 'A1', variableName: '主框架@宽度' },
    { cellRef: 'A2', variableName: '主框架@高度' },
    { cellRef: 'A3', variableName: '主框架@型号' },
    { cellRef: 'D8', variableName: '立柱片下@型号' }
  ]
  
  // 添加一个默认的批量表单
  addFormula()
  
  // 加载倍数规则
  loadBusinessRules()
}

init()
</script>

<style scoped lang="scss">
.formula-convert-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
  .header-content {
    text-align: center;
    
    .title-area {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 20px;
      margin-bottom: 10px;
    }
    
    .page-title {
      margin: 0;
      color: #303133;
      font-weight: 600;
    }
    .page-description {
      margin: 0;
      color: #606266;
      line-height: 1.6;
      
      code {
        background-color: #f5f5f5;
        padding: 2px 4px;
        border-radius: 3px;
        font-size: 12px;
      }
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.result-status {
  margin-top: 5px;
}

.batch-forms {
  .batch-form-item {
    margin-bottom: 15px;
    padding: 15px;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    background-color: #fafafa;

    .form-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      
      .form-index {
        font-weight: 600;
        color: #303133;
      }
    }
  }
}

.batch-results {
  margin-top: 20px;
  
  .result-summary {
    margin-bottom: 15px;
    
    .el-tag {
      margin-right: 10px;
    }
  }
  
  .result-actions {
    margin-top: 15px;
    text-align: right;
  }
}

.mapping-list {
  .mapping-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    
    .mapping-inputs {
      flex: 1;
      display: flex;
      align-items: center;
      gap: 10px;
      
      .mapping-arrow {
        color: #909399;
        font-weight: bold;
      }
    }
  }
}

.help-content {
  h4 {
    margin: 15px 0 10px 0;
    color: #303133;
    font-size: 14px;
  }
  
  .function-list {
    margin: 0;
    padding-left: 20px;
    
    li {
      margin-bottom: 5px;
      font-size: 12px;
      line-height: 1.6;
      
      code {
        background-color: #f5f5f5;
        padding: 2px 4px;
        border-radius: 3px;
        font-size: 11px;
      }
    }
  }
  
  .prefix-list {
    margin: 0;
    padding-left: 20px;
    
    li {
      margin-bottom: 5px;
      font-size: 12px;
      line-height: 1.6;
      
      code {
        background-color: #e6f7ff;
        padding: 2px 4px;
        border-radius: 3px;
        font-size: 11px;
      }
    }
  }
  
  .warning-list {
    margin: 0;
    padding-left: 20px;
    
    li {
      margin-bottom: 5px;
      font-size: 12px;
      line-height: 1.5;
      color: #e6a23c;
    }
  }
  
  .new-tag {
    display: inline-block;
    background: #52c41a;
    color: white;
    font-size: 9px;
    padding: 1px 3px;
    border-radius: 2px;
    margin-left: 5px;
    font-weight: bold;
  }
  
  .example-box {
    background: #f0f8ff;
    border: 1px solid #d6e4ff;
    border-radius: 6px;
    padding: 12px;
    margin: 10px 0;
    
    p {
      margin: 5px 0;
      font-size: 12px;
    }
  }
  
  .example-code {
    background: #f5f5f5;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    padding: 6px;
    display: block;
    font-family: 'Courier New', monospace;
    font-size: 10px;
    line-height: 1.4;
    word-break: break-all;
    white-space: pre-wrap;
    margin-top: 3px;
  }
  
  .help-text {
    margin: 10px 0;
    font-size: 12px;
    line-height: 1.6;
    color: #606266;
    
    code {
      background-color: #f5f5f5;
      padding: 2px 4px;
      border-radius: 3px;
      font-size: 11px;
    }
  }
}

// 特殊业务规则样式
.rules-management {
  .rules-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    
    span {
      font-weight: 600;
      color: #303133;
    }
  }
}

.business-examples {
  .example-item {
    margin-bottom: 20px;
    
    h5 {
      margin: 0 0 10px 0;
      color: #303133;
      font-size: 13px;
      font-weight: 600;
    }
    
    .example-code {
      background: #fafbfc;
      border: 1px solid #e1e4e8;
      border-radius: 6px;
      padding: 12px;
      font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
      font-size: 11px;
      line-height: 1.5;
      color: #24292e;
      overflow-x: auto;
      white-space: pre-wrap;
      word-break: break-all;
    }
  }
}

.rules-dialog-content {
  h4 {
    margin: 15px 0 10px 0;
    color: #303133;
    font-size: 14px;
    font-weight: 600;
  }
}

.dialog-footer {
  text-align: right;
}

// 电器公式转换样式
.electrical-batch {
  .batch-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    
    span {
      font-weight: 600;
      color: #303133;
    }
  }
}

.electrical-examples {
  .example-item {
    margin-bottom: 20px;
    
    h5 {
      margin: 0 0 10px 0;
      color: #303133;
      font-size: 13px;
      font-weight: 600;
    }
    
    .example-code {
      background: #fafbfc;
      border: 1px solid #e1e4e8;
      border-radius: 6px;
      padding: 12px;
      font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
      font-size: 11px;
      line-height: 1.5;
      color: #24292e;
      overflow-x: auto;
      white-space: pre-wrap;
      word-break: break-all;
    }
    
    .function-support {
      margin: 0;
      color: #606266;
      font-size: 12px;
      line-height: 1.6;
    }
  }
}
</style> 